using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ProMRDS.Simulation.Magellan
{
    public partial class SimMagellanUI : Form
    {
        FromWinformEvents _fromWinformPort;

        public SimMagellanUI(FromWinformEvents EventsPort)
        {
            _fromWinformPort = EventsPort;

            InitializeComponent();

            _fromWinformPort.Post(new FromWinformMsg(FromWinformMsg.MsgEnum.Loaded, null, this));
        }
        public void SetCameraImage(byte[] frame, ImageProcessResult result)
        {
            if (_cameraImage.Image == null)
                _cameraImage.Image = new Bitmap(320, 240, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            Bitmap bmp = (Bitmap)_cameraImage.Image;
            System.Drawing.Imaging.BitmapData bmd = bmp.LockBits(
                new Rectangle(0, 0, bmp.Width, bmp.Height),
                System.Drawing.Imaging.ImageLockMode.ReadWrite,
                bmp.PixelFormat);

            System.Runtime.InteropServices.Marshal.Copy(frame, 0, bmd.Scan0, frame.Length);

            bmp.UnlockBits(bmd);

            if (result.Area > result.AreaThreshold)
            {
                int size = (int)Math.Sqrt(result.Area);
                int offset = size / 2;
                Graphics grfx = Graphics.FromImage(bmp);
                grfx.DrawRectangle(Pens.White, result.XMean - offset, result.YMean - offset, size, size);
                grfx.DrawLine(Pens.White, result.XMean - 5, result.YMean, result.XMean + 5, result.YMean);
                grfx.DrawLine(Pens.White, result.XMean, result.YMean - 5, result.XMean, result.YMean + 5);
            }

            _cameraImage.Invalidate();
        }

        public void SetCurrentState(string state)
        {
            _stateLabel.Text = "State: " + state;
        }

        public void SetElapsedTime(string time)
        {
            _elapsedLabel.Text = time;
        }

        private void _startButton_Click(object sender, EventArgs e)
        {
            _fromWinformPort.Post(new FromWinformMsg(FromWinformMsg.MsgEnum.Start, null));
        }

        private void _resetButton_Click(object sender, EventArgs e)
        {
            _fromWinformPort.Post(new FromWinformMsg(FromWinformMsg.MsgEnum.Reset, null));
            _startButton.Enabled = true;
        }
    }
}